package com.booter.ws.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lcw
 * @date 2022/6/17 16:59
 */
@Slf4j
public final class SessionStore {

    /**
     * sessionId,user
     */
    private static Map<String, String> sessionIdUserMap = new ConcurrentHashMap<>();

    /**
     * user,sessionId
     */
    private static Map<String, String> userSessionIdMap = new ConcurrentHashMap<>();
    /**
     * sessionId,session
     */
    private static Map<String, CustomWebSocketSessionDecorator> sessionMap = new ConcurrentHashMap<>();

    public static void addUser(String sessionId, CustomWebSocketSessionDecorator decorator) {
        sessionMap.put(sessionId, decorator);
    }

    public static CustomWebSocketSessionDecorator getSession(String sessionId) {
        return sessionMap.get(sessionId);
    }

    public static void addSession(CustomWebSocketSessionDecorator decorator) {
        sessionMap.put(decorator.getId(), decorator);
        //todo 将用户先前登录的session清除，每个用户只能登录一个终端
    }

    public static String getSessionId(String userId) {
        return userSessionIdMap.get(userId);
    }

    public static String getUser(String sessionId) {
        return sessionIdUserMap.get(sessionId);
    }

    public static void removeUser(String user) {
        String sessionId = userSessionIdMap.get(user);
        sessionIdUserMap.remove(sessionId);
        removeSession(sessionId);
    }

    public static void removeSession(String sessionId) {
        try {
            CustomWebSocketSessionDecorator decorator = sessionMap.remove(sessionId);
            if (decorator == null) {
                return;
            }
            decorator.close(CloseStatus.GOING_AWAY);
        } catch (Exception ex) {
            log.error("关闭session异常", ex);
        }
    }
}
